package com.jt.auth.config;

import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.*;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import java.util.Arrays;

/**
 * @Usefulness: 在这个对象中负责将所有的认证和授权配置进行整合，例如
 *              1)SpringSecurity(提供认证和授权的实现)
 *              2)TokenConfig(提供了令牌的生成，存储，校验)
 *              3)Oauth2(定义了一套认证规范，例如为谁发令牌，都发什么，....)
 * @Author: LeiTing
 * @Date: 2021/9/27  10:46
 * @Version 1.0
 */
@AllArgsConstructor
@Configuration
@EnableAuthorizationServer
public class Oauth2Config extends AuthorizationServerConfigurerAdapter {
//POST http://localhost:9000/auth/oauth/token?username=jack&client_id=gateway-client&client_secret=123456&grant_type=password&password=123456
//    @Autowired
    private AuthenticationManager authenticationManager;
//    @Autowired
    private UserDetailsService userDetailsService;
//    @Autowired
    private TokenStore tokenStore;
//    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
//    @Autowired
    private JwtAccessTokenConverter jwtAccessTokenConverter;

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
//        super.configure(endpoints);
        endpoints.authenticationManager(authenticationManager)
                .userDetailsService(userDetailsService)
                .allowedTokenEndpointRequestMethods(HttpMethod.GET,HttpMethod.POST)
                .tokenServices(tokenService());
    }
    //定义令牌生成策略
    @Bean
    public AuthorizationServerTokenServices tokenService(){
        //构建tokenServices对象
        DefaultTokenServices tokenServices = new DefaultTokenServices();
        //设置令牌存储和生成策略
        tokenServices.setTokenStore(tokenStore);
        //设置是否支持令牌刷新
        tokenServices.setSupportRefreshToken(true);
        //设置令牌增强策略
        TokenEnhancerChain tokenEnhancer = new TokenEnhancerChain();
        tokenEnhancer.setTokenEnhancers(
                Arrays.asList(jwtAccessTokenConverter));

        tokenServices.setTokenEnhancer(tokenEnhancer);
        return tokenServices;
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
//        super.configure(security);
        //定义(公开)要认证的URL(permitAll()是官方定义好的)
        security.tokenKeyAccess("permitAll()") //return this
                //定义(公开)令牌检查的url
                .checkTokenAccess("permitAll()")
                //允许客户端直接通过表单方式提交认证
                .allowFormAuthenticationForClients();

    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
//        super.configure(clients);
        clients.inMemory()
                //定义客户端ID
                .withClient("gateway-client")
                //定义客户端密钥
                .secret(passwordEncoder.encode("123456"))
                //定义作用范围
                .scopes("all")
                //允许客户端基于密码方式，刷新令牌方式实现认证
                .authorizedGrantTypes("password","refresh_token");
    }
}



